<?php 
	include "inc/constants.inc.php";
	global $dateFormat;
	try{
	$url = $_GET['url'];
	$str = simplexml_load_file($url);
	$items = json_decode(json_encode($str), TRUE);
	//$items =  $str->channel->item;
	$news = $items['channel']['item'];
	
	global $newsCount, $attempted;
	$newsCount = 0;
	foreach($searchKeywordsSet as $searchKeywords)
	{
		if($newsCount == 0){
			fetchItems($news, $searchKeywords, $attempted);
		}
		else 
		{
			break;
		}
	}
	
		
	} catch (Exception $e) {
		//echo 'Caught exception: ',  $e->getMessage(), "\n";
	}
	function contains($input, array $referers)
	{
		foreach($referers as $referer) {
			if (stripos($input,$referer) !== false) {
				return true;
			}
		}
		return false;
	}
	
	function removeImg($content){
		$content = preg_replace("/<img[^>]+\>/i", "", $content);
		$content = preg_replace("/<br[^>]+\>/i", "", $content);
		$content = preg_replace("/<a[^>]+\>/i", "", $content);
		$content = substr($content, 0, 180);
		return $content."...";
	}
	
	function fetchItems($news, $searchedTopic, $attempted)
	{
		global $newsCount;
		STATIC $attempted;
		$newsAlreadyPrinted = array();
		$newsToPrint = array();
		foreach($news as $item)
		{
			if (contains($item['title'], $searchedTopic) && (!in_array($item['title'], $newsAlreadyPrinted)) ) {
				$newsCount++;
				$attempted++;
				array_push($newsAlreadyPrinted, $item['title']);
				array_push($newsToPrint, array("title" => $item['title'], "pubDate" => $item['pubDate'], "link" => $item['link'], "description" => removeImg($item['description'])));
			}	
		}
		if($newsCount>0)
			printNews($newsToPrint);
		
	}
	
	function printNews($news){
		global $dateFormat;
		echo "<ul class=\"featurettes\">";
		foreach($news as $newsItem)
		{
				echo "<li class=\"news-item\">";
				echo "<a href='".$newsItem['link']."' target=\"_new\">".$newsItem['title']."</a><br>";
				echo $newsItem['description']."<br>";
				echo "<span class=\"date\">".date($dateFormat, strtotime($newsItem['pubDate']))."</span>"."<br>";
				echo "</li>";
		}
		echo "</ul>";
	}
	
	function getKeywordToSearch($attempt, $searchKeywords)
	{
		switch ($attempt) {
			case 0 :
			return $searchKeywords['keywords_with_priority_1'];
			break;
			case 1 :
			return $searchKeywords['keywords_with_priority_2'];
			break;
			case 2 :
			return $searchKeywords['keywords_with_priority_3'];
			break;
		}
	}
?>